package com.nb.protocol.handle;

import com.nb.protocol.protocol.MessageHolder;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;
import java.util.List;

/**
 * Created by jwp on 2017/2/16.
 */
public class MessageUDPEncoder extends MessageToMessageEncoder<MessageHolder> {

    private final Charset charset;


    public MessageUDPEncoder() {
        this(CharsetUtil.UTF_8);
    }

    public MessageUDPEncoder(Charset charset) {
        if (charset == null) {
            throw new NullPointerException("charset");
        } else {
            this.charset = charset;
        }
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, MessageHolder msg, List<Object> out) throws Exception {
        ByteBuf byteBuf = Unpooled.buffer(256);


        // 编码

        byteBuf.writeBytes(msg.getRemoteAddr()).
                writeBytes(msg.getCpuIdBytes())
                .writeByte(msg.getSerial())
                .writeShort(msg.getFrame())
                .writeByte(msg.getType());

        //if (msg.getBody() != null) {
        //    byteBuf.writeBytes(msg.getBody());
        //}

        out.add(new DatagramPacket(byteBuf, msg.getSender()));
    }
}